package dl.bukkit.myststus.function.trigger;

import dl.bukkit.myststus.MyStatus;
import dl.bukkit.myststus.function.ComponentManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;

public class TriggerHandler implements Listener {
    private final Trigger<?> trigger;

    public TriggerHandler(Trigger<?> trigger) {
        this.trigger = trigger;
    }

    public void registerEvent(MyStatus plugin) {
        plugin.getServer().getPluginManager().registerEvent(
                trigger.getEvent(),
                this,
                EventPriority.HIGHEST,
                ComponentManager.getTriggerExecutor(this),
                plugin, true
        );
    }

    public final  <E extends Event> void apply(E event, Trigger<E> trigger, MyStatus plugin) {
        trigger.trigger(event);
        Player player = trigger.getPlayer(event);
        if (player == null) return;
        Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
            if (trigger.isRemove(event)) {
                trigger.remove(event);
            }else {
                trigger.send(event);
            }
        });
    }
}
